package com.Example;

import com.alibaba.fastjson.JSONObject;
import com.client.RepChainClient;
import com.client.RepChainJksClient;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.protos.Peer;
import org.apache.commons.codec.binary.Hex;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import static java.lang.Thread.sleep;


/**
 * 提交交易，构造交易字符串
 *
 * @author zyf
 */
public class GenerateTranString {
    public static void main(String[] args) {

        String host = "192.168.2.69:8081";
        RepChainJksClient client = new RepChainJksClient(host);
        client.setJks("jks/121000005l35120456.node1.jks", "123", "121000005l35120456.node1");
        Peer.CertId certId = Peer.CertId.newBuilder().setCreditCode("121000005l35120456").setCertName("node1").build(); // 签名ID

        try {

            String str_trans = Files.asCharSource(new File("Json/transfer_1.json"), Charsets.UTF_8).read(); // google的包,最新的Files.toString()即将废弃

            //这个是给转账交易示范用的，此ID需要与repchain合约部署的一致
            Peer.ChaincodeId contractAssetsId = Peer.ChaincodeId.newBuilder().setChaincodeName("ContractAssetsTPL").setVersion(1).build();

            FileWriter fw = new FileWriter(new File("D:/RepChainApi.txt"), true);
            BufferedWriter bw = new BufferedWriter(fw);

            for (int i = 0; i < 20000; i++) {
                // 构建转账交易1   chainCodeId 是部署好的合约的txid；
                Peer.Transaction transfer = client.createTransactionForInvoke(certId, contractAssetsId, "transfer", str_trans);
//                String transferStr = Hex.encodeHexString(transfer.toByteArray());
                //TODO 将数据写到txt中
                String out_transferStr = '"' + Hex.encodeHexString(transfer.toByteArray()) + '"';
                bw.write(out_transferStr);
                bw.write(System.lineSeparator());
//                bw.write("\n");
                //将交易数据post过去
//                sleep(15);
//                JSONObject transferResult = client.postTranByString(JSONObject.toJSONString(transferStr));
//                System.out.println(transferResult);
            }
            bw.close();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
    }
}
